package com.lz.sports.ui.config

import android.os.Bundle
import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.lz.comm.BR
import com.lz.library.base.BaseFragment
import com.lz.library.extension.click
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lz.sports.R
import com.lz.sports.adapter.DeviceManagerAdapter
import com.lz.sports.adapter.ListMoreAdapter
import com.lz.sports.bean.DeviceInfo
import com.lz.sports.databinding.FragmDeviceListBinding
import com.lz.sports.vm.config.DeviceListViewModel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

class DeviceListFragment : BaseFragment<DeviceListViewModel, FragmDeviceListBinding>(), com.lz.library.adapter.BaseAdapter.OnItemClickListener {

    private val moreAdapter by lazy { ListMoreAdapter(DeviceManagerAdapter()) }

    override fun getLayoutRes(): Int = R.layout.fragm_device_list

    override fun getVMVariableId(): Int = BR.vm

    override fun initObserve() {
        viewModel.pageListData.observe(this) {
            moreAdapter.setPageList(it)
            viewModel.totalCount.value = moreAdapter.adapter.data.size
            if (it.isRefreshing) binding.rvList.scrollToPosition(0)
        }
        LiveEventBus.get("DeviceInfo_Edit", DeviceInfo::class.java).observe(this) {
            (moreAdapter.adapter as DeviceManagerAdapter).update(it)
            viewModel.totalCount.value = moreAdapter.adapter.data.size
        }
        LiveEventBus.get("DeviceInfo_Delete", DeviceInfo::class.java).observe(this) {
            (moreAdapter.adapter as DeviceManagerAdapter).delete(it)
            viewModel.totalCount.value = moreAdapter.adapter.data.size
        }
    }

    override fun initData(savedState: Bundle?) {
        binding.rvList.adapter = moreAdapter.listAdapter
        moreAdapter.adapter.setOnItemClickListener(this)
        lifecycleScope.launch {
            arrayOf(binding.ivClear, binding.flSearch).click().collect {
                when (it.id) {
                    R.id.iv_clear -> { binding.etInput.setText(""); viewModel.clearSearch() }
                    R.id.fl_search -> viewModel.search()
                }
            }
        }
    }

    override fun onItemClick(view: View, position: Int) {
        val bundle = Bundle().apply {
            putParcelableArrayList("deviceInfoList", moreAdapter.adapter.data as ArrayList<DeviceInfo>)
            putInt("position", position)
        }
        findNavController().navigate(R.id.action_list_to_edit, bundle)
    }
}